/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.templateproject.fragment.trending;

import static java.lang.Thread.sleep;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;
import com.xuexiang.templateproject.R;
import com.xuexiang.templateproject.core.BaseFragment;
import com.xuexiang.templateproject.core.http.Chart;
import com.xuexiang.templateproject.core.http.UUIDmake;
import com.xuexiang.templateproject.databinding.FragmentGridItemBinding;
import com.xuexiang.templateproject.databinding.FragmentTrendingBinding;
import com.xuexiang.templateproject.utils.GlobalVars;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.button.ButtonView;
import com.xuexiang.xui.widget.dialog.bottomsheet.BottomSheet;
import com.xuexiang.xui.widget.dialog.bottomsheet.BottomSheetItemView;
import com.xuexiang.xui.widget.toast.XToast;
import com.xuexiang.xutil.tip.ToastUtils;
import com.zzhoujay.richtext.RichText;

import org.w3c.dom.Text;

import java.text.AttributedCharacterIterator;
import java.util.ArrayList;

/**
 * @author xuexiang
 * @since 2019-10-30 00:19
 */
@Page(anim = CoreAnim.none)
public class TrendingFragment extends BaseFragment<FragmentTrendingBinding> {

    ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
    String URL= GlobalVars.url;//TODO:改URL
    String urlTrend=URL+"trend";
    int walkP=0,lieP=0,stairP=0,runP=0,sitP=0,playP=100;
    @NonNull
    @Override
    protected FragmentTrendingBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentTrendingBinding.inflate(inflater, container, attachToRoot);
    }
    //显示底部列表对话框
    PieEntry pieEntry;
    private void showListDialog(){

        TextView text=new TextView(getContext());

        if(pieEntry.getLabel().equals("走路")){
//TODO:连接
            text.setText("  今日上下楼梯的时长达到了0.2小时,消耗热量2300\n焦耳,该运动量已达标");
            new BottomSheet.BottomListSheetBuilder(getContext(),true)
                    .setTitle("该日运动情况")
                    .addHeaderView(text)

//                .addItem(R.drawable.icon_more_operation_share_moment,"带图标的选项","文字tag")
                    //.setIsCenter(true)//文字居中对齐
                    .setCheckedIndex(2)//设置默认选中项，需要设置 needRightMark 为 true
                    .setOnSheetItemClickListener(new BottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                        @Override
                        public void onClick(BottomSheet dialog, View itemView, int position, String tag) {
                            dialog.dismiss();//关闭对话框
                        }
                    })
                    .setOnBottomDialogDismissListener(new DialogInterface.OnDismissListener() {
                        //对话框关闭时执行
                        //用户点击其他任意地方会关闭对话框
                        @Override
                        public void onDismiss(DialogInterface dialogInterface) {

                        }
                    })
                    .build().show();

        }

    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        return null;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ButtonView changeButton=findViewById(R.id.CB);
        Drawable Sport=getResources().getDrawable(R.drawable.sport2);
        changeButton.setForeground(Sport);
        changeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                XToastUtils.toast("再次点击图表即可完成刷新");
                if(changeButton.getForeground().equals(Sport)) {
                    Drawable Brain = getResources().getDrawable(R.drawable.brain);
                    changeButton.setForeground(Brain);
                    entries.clear();
                    entries.add(new PieEntry(25, "伤心"));
                    entries.add(new PieEntry(25, "平静"));
                    entries.add(new PieEntry(25, "愤怒"));
                    entries.add(new PieEntry(25, "开心"));

                    PieDataSet dataSet2 = new PieDataSet(entries, "数据说明");//右上角，依次排列

                    dataSet2.setDrawIcons(false);

                    dataSet2.setSliceSpace(0f);//设置饼状Item之间的间隙
                    dataSet2.setIconsOffset(new MPPointF(0, 40));
                    ArrayList<Integer> colors = new ArrayList<Integer>();

                    for (int c : ColorTemplate.VORDIPLOM_COLORS) {
                        colors.add(c);
                    }

                    for (int c : ColorTemplate.JOYFUL_COLORS) {
                        colors.add(c);
                    }

                    for (int c : ColorTemplate.COLORFUL_COLORS) {
                        colors.add(c);
                    }

                    for (int c : ColorTemplate.LIBERTY_COLORS) {
                        colors.add(c);
                    }

                    for (int c : ColorTemplate.PASTEL_COLORS) {
                        colors.add(c);
                    }

                    colors.add(ColorTemplate.getHoloBlue());

                    dataSet2.setColors(colors);
                    dataSet2.setSelectionShift(5f);//设置饼状Item被选中时变化的距离(为0f时，选中的不会弹起来)
                    PieData data2 = new PieData(dataSet2);//设置饼图里面的百分比（eg: 20.8%）
                    data2.setDrawValues(true);            //设置是否显示数据实体(百分比，true:以下属性才有意义)
                    data2.setValueTextColor(Color.WHITE);  //设置所有DataSet内数据实体（百分比）的文本颜色
                    data2.setValueTextSize(11f);          //设置所有DataSet内数据实体（百分比）的文本字体大小
//        data.setValueTypeface(mTfLight);     //设置所有DataSet内数据实体（百分比）的文本字体样式
                    data2.setValueFormatter(new PercentFormatter());//设置所有DataSet内数据实体（百分比）的文本字体格式
                    try {
                        sleep(100);
                        LinearLayout Tmp=findViewById(R.id.tmp);

                        FragmentTrendingBinding mBinding=FragmentTrendingBinding.bind(Tmp);
                        mBinding.pcCharts.setData(data2);// //为图表添加 数据

                    } catch (InterruptedException e) {
                        XToastUtils.toast("谁知道的错误"+e);
                    }
                }else{
                    changeButton.setForeground(Sport);
                    entries.clear();
                    entries.add(new PieEntry(stairP, "上下楼梯"));
                    entries.add(new PieEntry(walkP, "走路"));
                    entries.add(new PieEntry(runP, "跑步"));
                    entries.add(new PieEntry(sitP, "坐"));
                    entries.add(new PieEntry(playP  , "操作电脑"));
                    entries.add(new PieEntry(lieP, "躺"));
                    PieDataSet dataSet3 = new PieDataSet(entries, "数据说明");//右上角，依次排列

                    dataSet3.setDrawIcons(false);

                    dataSet3.setSliceSpace(0f);//设置饼状Item之间的间隙
                    dataSet3.setIconsOffset(new MPPointF(0, 40));
                    ArrayList<Integer> colors = new ArrayList<Integer>();

                    for (int c : ColorTemplate.VORDIPLOM_COLORS) {
                        colors.add(c);
                    }

                    for (int c : ColorTemplate.JOYFUL_COLORS) {
                        colors.add(c);
                    }

                    for (int c : ColorTemplate.COLORFUL_COLORS) {
                        colors.add(c);
                    }

                    for (int c : ColorTemplate.LIBERTY_COLORS) {
                        colors.add(c);
                    }

                    for (int c : ColorTemplate.PASTEL_COLORS) {
                        colors.add(c);
                    }

                    colors.add(ColorTemplate.getHoloBlue());

                    dataSet3.setColors(colors);
                    dataSet3.setSelectionShift(5f);//设置饼状Item被选中时变化的距离(为0f时，选中的不会弹起来)
                    PieData data3 = new PieData(dataSet3);//设置饼图里面的百分比（eg: 20.8%）
                    data3.setDrawValues(true);            //设置是否显示数据实体(百分比，true:以下属性才有意义)
                    data3.setValueTextColor(Color.WHITE);  //设置所有DataSet内数据实体（百分比）的文本颜色
                    data3.setValueTextSize(11f);          //设置所有DataSet内数据实体（百分比）的文本字体大小
//        data.setValueTypeface(mTfLight);     //设置所有DataSet内数据实体（百分比）的文本字体样式
                    data3.setValueFormatter(new PercentFormatter());//设置所有DataSet内数据实体（百分比）的文本字体格式
                    try {
                        sleep(100);
                        LinearLayout Tmp=findViewById(R.id.tmp);

                        FragmentTrendingBinding mBinding=FragmentTrendingBinding.bind(Tmp);
                        mBinding.pcCharts.setData(data3);// //为图表添加 数据

                    } catch (InterruptedException e) {
                        XToastUtils.toast("谁知道的错误"+e);
                    }
                }
            }
        });
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initViews() {
        Chart tmp=new Chart();
        LinearLayout Tmp=findViewById(R.id.tmp);

        FragmentTrendingBinding mBinding=FragmentTrendingBinding.bind(Tmp);
//         Android 4.0 之后不能在主线程中请求HTTP请求
        new Thread(() -> {try {
            try {
                Log.e("222","在它执行之前就挂了");

                String[] retval=tmp.run(urlTrend,"type","act","UUID",UUIDmake.readKey()).split(",");
                stairP= Integer.parseInt(retval[0]);
                walkP= Integer.parseInt(retval[1]);
                runP= Integer.parseInt(retval[2]);
                sitP= Integer.parseInt(retval[3]);
                playP= Integer.parseInt(retval[4]);
                lieP= Integer.parseInt(retval[5]);
                if(entries.isEmpty()){
                    entries.add(0,new PieEntry(stairP, "上下楼梯"));
                    entries.add(1,new PieEntry(walkP, "走路"));
                    entries.add(2,new PieEntry(runP, "跑步"));
                    entries.add(3,new PieEntry(sitP, "坐"));
                    entries.add(4,new PieEntry(playP  , "操作电脑"));
                    entries.add(5,new PieEntry(lieP, "躺"));
                }else {

                    entries.set(0, new PieEntry(stairP, "上下楼梯"));
                    entries.set(1, new PieEntry(walkP, "走路"));
                    entries.set(2, new PieEntry(runP, "跑步"));
                    entries.set(3, new PieEntry(sitP, "坐"));
                    entries.set(4, new PieEntry(playP, "操作电脑"));
                    entries.set(5, new PieEntry(lieP, "躺"));
                }
            }catch (RuntimeException e){
                ToastUtils.toast("无法连接到服务器1");
                stairP= 0;
                walkP= 0;
                runP= 0;
                sitP= 0;
                playP= 0;
                lieP= 100;
            }



            //清除数据
            //添加数据


        } catch (Exception e) {
            ToastUtils.toast("无法连接到服务器3");
            Log.e("err",e.toString());
            stairP= 0;
            walkP= 0;
            runP= 0;
            sitP= 0;
            playP= 0;
            lieP= 100;
        }

        }).start();

        entries.add(new PieEntry(stairP, "上下楼梯"));
        entries.add(new PieEntry(walkP, "走路"));
        entries.add(new PieEntry(runP, "跑步"));
        entries.add(new PieEntry(sitP, "坐"));
        entries.add(new PieEntry(playP  , "操作电脑"));
        entries.add(new PieEntry(lieP, "躺"));

        mBinding.pcCharts.setUsePercentValues(true); //设置是否显示数据实体(百分比，true:以下属性才有意义)
        mBinding.pcCharts.getDescription().setEnabled(false);//设置pieChart图表的描述
        mBinding.pcCharts.setExtraOffsets(5, 10, 5, 0);//饼形图上下左右边距

        mBinding.pcCharts.setDragDecelerationFrictionCoef(0.92f);//设置pieChart图表转动阻力摩擦系数[0,1]

//        mBinding.pcCharts.setCenterTextTypeface(mTfLight);//设置所有DataSet内数据实体（百分比）的文本字体样式
        mBinding.pcCharts.setCenterText("饼状图");//设置PieChart内部圆文字的内容

        mBinding.pcCharts.setDrawHoleEnabled(true);//是否显示PieChart内部圆环(true:下面属性才有意义)
        mBinding.pcCharts.setHoleColor(Color.WHITE);//设置PieChart内部圆的颜色

        mBinding.pcCharts.setTransparentCircleColor(Color.WHITE);//设置PieChart内部透明圆与内部圆间距(31f-28f)填充颜色
        mBinding.pcCharts.setTransparentCircleAlpha(0);//设置PieChart内部透明圆与内部圆间距(31f-28f)透明度[0~255]数值越小越透明
        mBinding.pcCharts.setHoleRadius(0f);//设置PieChart内部圆的半径(这里设置0f,即不要内部圆)
        mBinding.pcCharts.setTransparentCircleRadius(31f);//设置PieChart内部透明圆的半径(这里设置31.0f)

        mBinding.pcCharts.setDrawCenterText(true);//是否绘制PieChart内部中心文本（true：下面属性才有意义）

        mBinding.pcCharts.setRotationAngle(0);//设置pieChart图表起始角度

        mBinding.pcCharts.setRotationEnabled(true);//设置pieChart图表是否可以手动旋转
        mBinding.pcCharts.setHighlightPerTapEnabled(true);//设置piecahrt图表点击Item高亮是否可用

        mBinding.pcCharts.animateY(1400, Easing.EaseInOutQuad);// 设置pieChart图表展示动画效果
//         mBinding.pcCharts.spin(2000, 0, 360);//旋转

        // 获取pieCahrt图列(图列的位置、是水平还是垂直显示)
        Legend l = mBinding.pcCharts.getLegend();
        l.setForm(Legend.LegendForm.LINE);//线性
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);//上边
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);//右边（跟着TOP既是右上角，根据自己需求设置左上角、左下角……）
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f); //设置图例实体之间延X轴的间距（setOrientation = HORIZONTAL有效）
        l.setYEntrySpace(0f); //设置图例实体之间延Y轴的间距（setOrientation = VERTICAL 有效）
        l.setYOffset(0f);//设置比例块Y轴偏移量


        mBinding.pcCharts.setEntryLabelColor(Color.WHITE);//设置pieChart图表文本字体颜色
//        mBinding.pcCharts.setEntryLabelTypeface(mTfRegular);//设置pieChart图表文本字体样式
        mBinding.pcCharts.setEntryLabelTextSize(14.5f);//设置pieChart图表文本字体大小

        PieDataSet dataSet = new PieDataSet(entries, "数据说明");//右上角，依次排列

        dataSet.setDrawIcons(false);

        dataSet.setSliceSpace(0f);//设置饼状Item之间的间隙
        dataSet.setIconsOffset(new MPPointF(0, 40));

        dataSet.setSelectionShift(5f);//设置饼状Item被选中时变化的距离(为0f时，选中的不会弹起来)

        ArrayList<Integer> colors = new ArrayList<Integer>();

        for (int c : ColorTemplate.VORDIPLOM_COLORS) {
            colors.add(c);
        }

        for (int c : ColorTemplate.JOYFUL_COLORS) {
            colors.add(c);
        }

        for (int c : ColorTemplate.COLORFUL_COLORS) {
            colors.add(c);
        }

        for (int c : ColorTemplate.LIBERTY_COLORS) {
            colors.add(c);
        }

        for (int c : ColorTemplate.PASTEL_COLORS) {
            colors.add(c);
        }

        colors.add(ColorTemplate.getHoloBlue());

        dataSet.setColors(colors);

        PieData data = new PieData(dataSet);//设置饼图里面的百分比（eg: 20.8%）
        data.setDrawValues(true);            //设置是否显示数据实体(百分比，true:以下属性才有意义)
        data.setValueTextColor(Color.WHITE);  //设置所有DataSet内数据实体（百分比）的文本颜色
        data.setValueTextSize(11f);          //设置所有DataSet内数据实体（百分比）的文本字体大小
//        data.setValueTypeface(mTfLight);     //设置所有DataSet内数据实体（百分比）的文本字体样式
        data.setValueFormatter(new PercentFormatter());//设置所有DataSet内数据实体（百分比）的文本字体格式

        mBinding.pcCharts.setData(data);// //为图表添加 数据

        mBinding.pcCharts.highlightValues(null);//设置高亮显示
        mBinding.pcCharts.setDrawEntryLabels(true);// 设置pieChart是否只显示饼图上百分比不显示文字
        mBinding.pcCharts.invalidate();//将图表重绘以显示设置的属性和数据

        mBinding.pcCharts.setOnChartValueSelectedListener(new OnChartValueSelectedListener() {//点击事件
        ButtonView changeButton=findViewById(R.id.CB);
        @SuppressLint("UseCompatLoadingForDrawables")
        Drawable Brain=getResources().getDrawable(R.drawable.brain);



            @Override
            public void onValueSelected(Entry e, Highlight h) {
                pieEntry = (PieEntry) e;
                showListDialog();
//                if (pieEntry.getLabel().equals("走路")){
//                    TextView health=findViewById(R.id.healthtext);
//                    RichText.fromHtml(walktext).bind(this).into(health);
//                    BottomSheetItemView details=findViewById(R.id.details);
//                    Animation out=AnimationUtils.loadAnimation(getContext(),R.anim.out);
//                    details.setAnimation(out);
//                    details.startAnimation(out);
            }


            @Override
            public void onNothingSelected() {

            }
        });

    }


}

